package com.wwzl.mqttsend5.controller;

import com.wwzl.mqttsend5.mqtt.MqttConsumer;
import com.wwzl.mqttsend5.mqtt.MqttSubMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * 对外接口
 */
@RequestMapping("/mqtt")
@RestController
public class PublicController {
    /**
     * 发布消息
     *
     * @return
     */
    @RequestMapping(value = "/testPublish")
    public String testPublish(String deviceName) throws InterruptedException {
        System.out.println("---------------------------------");
        String s = UUID.randomUUID().toString();
        System.out.println("UUID:" + s);
        String msg2 = "sensor/" + deviceName + "/request/resetPulses/" + s;
        MqttConsumer.publish(msg2, "");
        System.out.println("发送了一条主题是:" + msg2);
        String msg3 = "sensor/" + deviceName + "/response/resetPulses/" + s;
        String val;
        int flag = 0;
        Thread.sleep(200);
        while (true) {
            val = MqttSubMap.mqttSub.get(msg3);
            if (val != null) {
                MqttSubMap.mqttSub.remove(msg3);
                break;
            }
            flag++;
            if (flag == 500) {
                //找500次休眠1秒
                System.out.println(s + ":找了500次了！！！！！");
                Thread.sleep(5000);
            }
            if (flag == 1000) {
                //找1000次找不到结束循环
                System.out.println(s + ":找了1000次了！！！！！");
                val = "false";
                break;
            }
        }
        System.out.println("------------------------------");
        return val;
    }

    /**
     * 订阅主题
     *
     * @param topic 主题
     * @param qos   消息级别
     * @return
     */
    @RequestMapping(value = "testSubsribe")
    public String testSubsribe(String topic, int qos) {
        MqttConsumer.subscribe(topic, qos);
        return "订阅'" + topic + "'成功";
    }


}
